package com.jacky.androidutils.utils.io;

import android.os.Environment;

import com.jacky.androidutils.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class FileUtils2 {
	public static final String CACHE = "cache";
	public static final String ICON = "icon";
	public static final String APP = ContextUtils.getResource().getString(R.string.app_name);
	
	public static File getCacheDir() {
		return getDir(CACHE);
	}
	public static File getIconDir() {
		return getDir(ICON);
	}
	
	public static File getDir(String dir) {
		StringBuilder path = new StringBuilder();
		if(isSDAvailable()) {
			//SD卡可用,文件在/APP/dir/
			path.append(Environment.getExternalStorageDirectory().getAbsolutePath());
			path.append(File.separator);
			path.append(APP);
			path.append(File.separator);
			path.append(dir);
			
		}else {
			//文件在data/data/<包名>/cache/dir
			File cacheDir = ContextUtils.getContext().getCacheDir();
			path.append(cacheDir.getAbsolutePath());
			path.append(File.separator);
			path.append(dir);
		}
		File file = new File(path.toString());
		if(!file.exists() || !file.isDirectory()){
			file.mkdirs();
		}
		return file;
	}
	
	public static boolean isSDAvailable() {
		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			return true;
		}else {
			return false;
		}
	}
	/**
	 * 把流转换为字符串
	 * @param is
	 * @return
	 */
	public static String readSreamAsString(InputStream is) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int len = 0;
		byte[] bys = new byte[1024];
		try {
			if((len = is.read(bys)) != -1) {
				baos.write(bys);
			}
			byte[] temp = baos.toByteArray();
			return new String(temp);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * md5加密方法
	 * @param password
	 * @return
	 */
	public static String md5(String password) {

		try {
			// 得到一个信息摘要器
			MessageDigest digest = MessageDigest.getInstance("md5");
			byte[] result = digest.digest(password.getBytes());
			StringBuffer buffer = new StringBuffer();
			// 把没一个byte 做一个与运算 0xff;
			for (byte b : result) {
				// 与运算
				int number = b & 0xff;// 加盐
				String str = Integer.toHexString(number);
				// System.out.println(str);
				if (str.length() == 1) {
					buffer.append("0");
				}
				buffer.append(str);
			}

			// 标准的md5加密后的结果
			return buffer.toString();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		}

	}
}
